<template>
  <div class="publish-warpper clearfix">
    <div class="photoBox clearfix">
     	<div class="photoSecBox">
     		<div class="bgBox">
          <div :class="[logo?'hide':'','camera']">
            <input type="file" name="font" accept="image/*" @change='addImg($event,"fontImg","fontImg2")'>
          </div>
     			<!-- <img v-if="true" class="camera" src="../assets/images/second_carmar.png"> -->
          <span>添加图片</span>
     		</div>
     		<img v-if="logoImg" src="">
     	</div>
      <div class="imgArrBox">
        <div class="imgItemBox" v-if="imgArr.length>0" v-for="(item,index) in imgArr">
          <img :src="item" >
        </div>
        <div class="addicon">
          <input type="file" name="font" multiple accept="image/*" @change='addImg($event,"fontImg","fontImg2")'>
        </div>
      </div>
    </div>
    <group class="marginB">
      <x-input placeholder="宝贝标题、品牌型号"  show-clear v-model="name"></x-input>
      <x-textarea placeholder="在这里描述转手宝贝,比如转手原因、入手渠道、规格尺寸、新旧程度和使用感受，会增加曝光度哦~" v-model="detailInfo"></x-textarea>
      <div class="checkBar flex">
      	<div class="leftBox flex">
      		<img src="../assets/images/add.png">
      		<span v-if="shopInfo">{{shopInfo.schoolName}}</span>
      	</div>
      	<check-icon :value.sync="isNew">全新宝贝</check-icon>
      </div>
      <div class="fengeBar"></div>
      <!-- <cell title="分类"  value="选择分类" is-link></cell> -->
      <popup-picker title="分类" :data="kindListArr" v-model="firstKind" @on-change="changeKind($event)" placeholder="选择分类"></popup-picker>
      <cell title="价格" @click.native="openPriceDialog" :value="priceText" is-link></cell>
    </group>
    <div class="bom-box" @click="handleConfirm">
      <span>{{comfirmText}}</span>
    </div>
    <div>
      <x-dialog :show.sync="editPrice" hide-on-blur :dialog-style="{'max-width': '100%', width: '100%', height: 'auto', 'background-color': 'transparent'}" class="dialog-demo" @on-hide="handleClose">
        <div class="img-box">
	        <group>
		      <x-input title="¥:" placeholder="给宝贝出个价吧" type="number" show-clear v-model="money"></x-input>
		      <x-input title="原价:" placeholder="¥:0" show-clear type="number"  v-model="oldPrice"></x-input>
		      <x-input title="运费:" placeholder="¥:0" show-clear type="number" v-model="postPrice">
		      	<!-- <check-icon slot="right" :value.sync="isFreeSend">包邮</check-icon> -->
		      </x-input>
		    </group>
		    <x-icon @click="editPrice=false" type="ios-close-outline" style="fill:#fff;margin-top: 8px;"></x-icon>
        </div>
        <!-- <div @click="editPrice=false">
          <span class="vux-close">确定</span>
        </div> -->
      </x-dialog>
    </div>
  </div>
</template>

<script>
  import axios from '@/api/request'
  import fetch from '@/utils/fetch'
  import { Tab,Group,XInput,XTextarea,Cell,CheckIcon,XDialog,PopupPicker } from "vux";
  import Exif from 'exif-js'
  import { mapState } from "vuex";

  export default {
    name: '',
    components: {
      Group,Cell,XInput,XTextarea,CheckIcon,XDialog,PopupPicker
    },
    data () {
      return {
        name: '',
        detailInfo: '',
        comfirmText: '',
        isNew: false,
        logo: false,
        logoImg: '',
        editPrice: false,
        money: '',
        oldPrice: '',
        freight: '',
        postPrice: '',
        isFreeSend: false,
        kindList: [],
        firstKind: [],
        firstKindId: "",
        kindList1: [[1,2,3,4,5,6]],
        kindListArr: [],
        shopId: '',
        imgArr: [],
        imgArr2: [],
        shopInfo: null,
        _userId: null,
        goodsId: '',
        goodsInfo: null,
        detailImgs: [],
        priceText: ''
      }
    },
    computed:{
        ...mapState({
          openId:state=>state.openId,
          userId:state=>state.userId,
          schoolId:state=>state.schoolId,
        }),
    },
    created(){
      this._userId = this.$route.query.userId
      this.goodsId = this.$route.query.goodsId
      if(!this._userId){
        this._userId = this.userId
      }
      if(this.goodsId){
        this.getGoodsInfo(this.goodsId)
        this.comfirmText = "保存"
      }else{
        this.priceText = '开个价'
        this.comfirmText = "发布商品"
      }
    },
    mounted(){
      this.fetchKindList()
      this.getshopInfobyUserid()
    },
    methods:{
      getGoodsInfo(id){   //获取商品信息
        var self=this 
        axios('/device/productSecond/getById','post',{id: id}).then(res=>{
          if(res.data.code==1000){
            console.log(res)
            this.goodsInfo = res.data.data.product
            this.name = this.goodsInfo.name
            this.detailInfo = this.goodsInfo.description
            let a = []
            a.push(this.goodsInfo.firstKindName)
            this.firstKind = a
            this.changeKind(a)
            this.isNew = this.goodsInfo.isNew==0? false:true
            this.money = this.goodsInfo.discountPrice
            this.oldPrice = this.goodsInfo.price
            this.priceText = this.goodsInfo.discountPrice
            this.postPrice = this.goodsInfo.postPrice
            this.detailImgs = JSON.parse(res.data.data.product.detailImgs)
            this.imgArr = JSON.parse(res.data.data.product.detailImgs)
            this.imgArr2 = this.detailImgs
            console.log(this.detailImgs)
          }
        })
      },
      fetchKindList() {
        axios('/device/kindSecond/firstCatalog','post',{}).then(res=>{
          if(res.data.code==1000){
            // console.log(res)
            this.kindList = res.data.data
            this.kindListArr.push(this.obj2arr(res.data.data))
          }
        })
      },
      getshopInfobyUserid() {
        let id = this._userId
        axios('/device/shopSecond/getSSbyUid/'+id,'post',{}).then(res=>{
          if(res.data.code==1000){
            console.log(123)
            console.log(res)
            this.shopInfo = res.data.data
            // this.shopId = res.data.data.shopSecondId
          }
        })
      },
      addImg(e,img,img2){ 
        let files = e.target.files || e.dataTransfer.files;  
        if (!files.length) return; 
        this.uploadImg(files,img2).then(res=>{
          console.log(res)
          // img2 = res.data
          // this[img2] = res.data
          let str = fetch.defaults.baseURL+res.data
          this.imgArr2.push(str)
          console.log(123)
          console.log(this.imgArr2)
        }) 
        this.picValue = files[0];  
        this.imgPreview(this.picValue,img);
      },
      handleConfirm(){  //发布商品
        let data = {
          shopId: this.shopInfo.id,    //店铺ID
          shopName: this.shopInfo.shopName,    //店铺名
          name: this.name,     //产品名称
          logo: this.imgArr2[0],         //产品LOGO
          price: this.oldPrice,          //产品原价
          discountPrice: this.money,   //产品折后价
          stock: 1,
          isNew: this.isNew? 1:0,
          postPrice: this.postPrice || 0,
          description: this.detailInfo,
          detailImgs: JSON.stringify(this.imgArr2),
          // detailImgs: JSON.stringify(this.detailImgs),
          createUser: this.shopInfo.username,  //真是姓名
          schoolId: this.schoolId,   //学校id
          shopType: '735279aea3ef4c7fb780b120f9b160a1',   //店铺类型
          userId: this._userId,    //用户ID
          firstKindId: this.firstKindId, //一级ID
          firstKindName: this.firstKindName,     //一级Name
        }
        // console.log(data)
        if(data.name&&data.logo&&data.price&&data.discountPrice&&data.firstKindId&&data.description){
          if(this.goodsId){
            data.id = this.goodsId
          }
          axios('/device/productSecond/saveOrUpdate','post',data).then(res=>{
            if(res.data.code==1000){
                console.log(res)
                if(this.goodsId){
                  this.$vux.toast.text('修改成功', 'middle')
                }else{
                  this.$vux.toast.text('添加成功', 'middle')
                }
                this.$router.go(-1)   //返回
            }
          })
        }else{
          this.$vux.toast.text('请填完整再提交', 'middle')
        }
      },
      openPriceDialog(){
      	this.editPrice = true
      },
      handleClose() {
        this.priceText = this.money
      },
      changeKind(e) {
        console.log(e)
        this.firstKindName = e[0]
        let kindId = this.name2id(e[0],this.kindList)
        this.firstKindId = kindId
        console.log(kindId)
      },
      obj2arr(arr){
        let newArr = []
        for(let i in arr){
          newArr.push(arr[i].name)
        }
        return newArr
      },
      name2id(name,arr) {
        for(let i in arr){
          if(name ==arr[i].name){
            return arr[i].id
          }
        }
      },
      imgPreview (file,imgsrc) {  
        let self = this;
        let Orientation;  
        //去获取拍照时的信息，解决拍出来的照片旋转问题  
        Exif.getData(file, function(){  
            Orientation = Exif.getTag(this, 'Orientation');  
        });  
        // 看支持不支持FileReader  
        if (!file || !window.FileReader) return;  
  
        if (/^image/.test(file.type)) {  
          // 创建一个reader  
          let reader = new FileReader(); 

          // 将图片2将转成 base64 格式  
          reader.readAsDataURL(file);  
          // 读取成功后的回调  
          reader.onloadend = function () {  
            let result = this.result;  
            let img = new Image();  
            img.src = result;  
            //判断图片是否大于100K,是就直接上传，反之压缩图片  
            if (this.result.length <= (100 * 1024)) {  
              // self.fontImg = this.result; 
              // self[imgsrc] = this.result; 
              self.imgArr.push(this.result)
              // self.postImg(self,this.result);  
            }else {  
              img.onload = function () {  
                let src = self.compress(img,Orientation);  
                // self[imgsrc] = self.compress(img,Orientation); 
                self.imgArr.push(self.compress(img,Orientation))
                // self.fontImg = src;  
                // self.postImg(self,src);  
              }  
            }  
          }   
        }  
      },
      compress(img,Orientation) {  
        let self = this
        let canvas = document.createElement("canvas");  
        let ctx = canvas.getContext('2d');  
        //瓦片canvas  
        let tCanvas = document.createElement("canvas");  
        let tctx = tCanvas.getContext("2d");  
        let initSize = img.src.length;  
        let width = img.width;  
        let height = img.height;  
        //如果图片大于四百万像素，计算压缩比并将大小压至400万以下  
        let ratio;  
        if ((ratio = width * height / 4000000) > 1) {  
          console.log("大于400万像素")  
          ratio = Math.sqrt(ratio);  
          width /= ratio;  
          height /= ratio;  
        } else {  
          ratio = 1;  
        }  
        canvas.width = width;  
        canvas.height = height;  
        //   铺底色  
        ctx.fillStyle = "#fff";  
        ctx.fillRect(0, 0, canvas.width, canvas.height);  
          //如果图片像素大于100万则使用瓦片绘制  
        let count;  
        if ((count = width * height / 1000000) > 1) {  
          console.log("超过100W像素");  
          count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片  
          //       计算每块瓦片的宽和高  
          let nw = ~~(width / count);  
          let nh = ~~(height / count);  
          tCanvas.width = nw;  
          tCanvas.height = nh;  
          for (let i = 0; i < count; i++) {  
            for (let j = 0; j < count; j++) {  
              tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);  
              ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);  
            }  
          }  
        } else {  
          ctx.drawImage(img, 0, 0, width, height);  
        }  
        //修复ios上传图片的时候 被旋转的问题  
        if(Orientation != "" && Orientation != 1){  
          switch(Orientation){  
            case 6://需要顺时针（向左）90度旋转  
                this.rotateImg(img,'left',canvas);  
                break;  
            case 8://需要逆时针（向右）90度旋转  
                this.rotateImg(img,'right',canvas);  
                break;  
            case 3://需要180度旋转  
                this.rotateImg(img,'right',canvas);//转两次  
                this.rotateImg(img,'right',canvas);  
                break;  
          }  
        }  
        //进行最小压缩  
        let ndata = canvas.toDataURL('image/jpeg', 0.1);  
        console.log('压缩前：' + initSize);  
        console.log('压缩后：' + ndata.length);  
        console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");  
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;  
        self.fontReady = true
        return ndata;  
      },
      rotateImg (img, direction,canvas) {  
        //最小与最大旋转方向，图片旋转4次后回到原方向      
        const min_step = 0;      
        const max_step = 3;        
        if (img == null)return;      
        //img的高度和宽度不能在img元素隐藏后获取，否则会出错      
        let height = img.height;      
        let width = img.width;        
        let step = 2;      
        if (step == null) {      
            step = min_step;      
        }      
        if (direction == 'right') {      
            step++;      
            //旋转到原位置，即超过最大值      
            step > max_step && (step = min_step);      
        } else {      
            step--;      
            step < min_step && (step = max_step);      
        }       
        //旋转角度以弧度值为参数      
        let degree = step * 90 * Math.PI / 180;      
        let ctx = canvas.getContext('2d');      
        switch (step) {      
          case 0:      
              canvas.width = width;      
              canvas.height = height;      
              ctx.drawImage(img, 0, 0);      
              break;      
          case 1:      
              canvas.width = height;      
              canvas.height = width;      
              ctx.rotate(degree);      
              ctx.drawImage(img, 0, -height);      
              break;      
          case 2:      
              canvas.width = width;      
              canvas.height = height;      
              ctx.rotate(degree);      
              ctx.drawImage(img, -width, -height);      
              break;      
          case 3:      
              canvas.width = height;      
              canvas.height = width;      
              ctx.rotate(degree);      
              ctx.drawImage(img, -width, 0);      
              break;  
        }      
      },
    }
  };
</script>

<style >
    body{
        position: absolute;
        left: 0;
        top: 0;
        /*background: rgb(244,244,244);*/
        width: 100%;
        height: 100%;
        overflow: hidden;
    }
    .publish-warpper .weui-cells{
      margin-top: 10px;
      /*margin-bottom: 1.3333rem;*/
    }
    .publish-warpper .marginB{
      /*margin-bottom: 1.3333rem;*/
      padding-bottom: 1.3333rem;
    }
</style>
<style lang="less" scoped>
  .publish-warpper{
    // height: 100%;
    height: auto;
    box-sizing: border-box;
    // padding-top: 20rem/75;
    background: rgb(244,244,244);
	  .photoBox{
    .imgArrBox{
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      margin-bottom: 8px;
      .addicon{
        background: #fff;
        width: 180rem/75;
        height: 180rem/75;
        line-height: 180rem/75;
        margin-left: 6rem/75;
        margin-bottom: 6rem/75;
        font-size: 60rem/75;
        text-align: center;
        border-radius: 4px;
        border: 1.5px dashed #ddd;
        position: relative;
        input{
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
          opacity: 0;
          width: 100%;
          height: 100%;
          z-index: 99;
        }
      }
      .addicon:after{
        width: 180rem/75;
        height: 180rem/75;
        line-height: 180rem/75;
        position: absolute;
        left: 0;
        top: 0;
        content: '+';
        font-size: 60rem/75;
        color: #2c3e50;
        z-index: 0;
      }
      .imgItemBox{
        width: 180rem/75;
        height: 180rem/75;
        margin-left: 6rem/75;
        margin-bottom: 10rem/75;
        border: 1.5px dashed #ddd;
        img{
          width: 100%;
          height: 100%;
        }
      }
    }
		.photoSecBox{
      height: 82rem/37.5;
			display: flex;
			flex-direction:column;
			align-items: center;
		}
		min-height: 240rem/75;
		background: #fff;
    .bgBox{
      width: 100%;
      height: 100%;
      text-align: center;
      div{
        width: 82rem/75;
        height: 66rem/75;
        margin-top: 49rem/75;
        margin-left: calc(50% - 41rem/75);
        background: url(../assets/images/second_carmar.png) no-repeat;
        background-size: 100% 100%;
        input{
          width: 100%;
          height: 100%;
          height: 96rem/75;
          opacity: 0;
        }
      }
    }
	}

	.vux-x-textarea.weui-cell{
		min-height: 360rem/75;
	}

    div.weui-cells{
      margin-top: 5px;
    }
    div.vux-x-switch.weui-cell.weui-cell_switch:before{
      border-top: 0;
    }
    .checkBar{
    	height: 80rem/75;
      align-items: center;
      display:flex;
      padding:0 35rem/75;
      
    	.leftBox{
        align-items: center;
        flex:1;
    	}
    	img{
    		width: 24rem/75;
    		height: 30rem/75;
    	}
    }
    .fengeBar{
      height: 10px;
      background: rgb(244,244,244);
    }
    .bom-box{
	  position: fixed;
	  left: 0;
	  bottom: 0;
	  width: 100%;
      height: 95rem/75;
      line-height: 95rem/75;
      background: #ff6053;
      color: #fff;
      text-align: center;
      font-size: 35rem/75;
    }
  }

</style>

